package com.heima.kafka.sample;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.*;
import org.junit.Test;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class KafkaStreamQuickStart {

    @Test
    public void quickStart() throws InterruptedException {
        //2. 构建配置参数
        Properties props = new Properties();
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-quickstart");

        //3. 创建streambuilder对象并设置流式计算的方法
        StreamsBuilder streamsBuilder = new StreamsBuilder();
        //设置具体的流式计算
        streamProcessor(streamsBuilder);

        //1. 创建KafkaStreams核心对象
        KafkaStreams kafkaStreams = new KafkaStreams(streamsBuilder.build(), props);

        //4. 启动流式计算
        kafkaStreams.start();

        TimeUnit.SECONDS.sleep(10000);
    }

    private void streamProcessor(StreamsBuilder streamsBuilder) {
        //1. 监听某一个topic
        KStream<String, String> stream = streamsBuilder.stream("itcast-topic-input");

        //2. 对消息进行处理
        stream.flatMapValues(new ValueMapper<String, Iterable<?>>() {
            @Override
            public Iterable<?> apply(String value) {
                return Arrays.asList(value.split(" "));
            }
        })
                .groupBy((key, value) -> value)   //3. 统计分析
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                .count()
                .toStream()  //4. 把结果转换位KStream类型的对象
                .map((key, value) -> new KeyValue<>(key.key().toString(), value.toString()))
                .to("itcast-topic-out"); //5. 把结果写到一个新的topic中进行存储

    }
}
